
package com.team.ai.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import com.team.ai.controller.vo.SmsCodeVO;
import com.team.ai.entity.User;
import com.team.ai.exception.BusinessException;
import com.team.ai.exception.BusinessExceptionEnum;
import com.team.ai.service.UserService;
import com.team.ai.service.util.AliyunSMSUtil;
import com.team.ai.service.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Slf4j
@CrossOrigin
@RestController
@Api(value = "v1", tags = "09.短信服务Web接口")
@RequestMapping("/app/v1/sms")
public class SMSController {

    @Resource
    private UserService userService;

    @Resource
    private AliyunSMSUtil smsUtil;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Value("${aliyun.sms.timeOut}")
    private String timeOut;

    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "获取短信验证码", notes = "通过阿里云短信服务获取验证码")
    @ApiImplicitParam(name = "phone", value = "手机号码", dataType = "String", required = true)
//    @SaCheckLogin
    @GetMapping("/code")
    public Result<SmsCodeVO> getSmsCode(String phone) throws ExecutionException, InterruptedException {
        log.info(phone);
        SmsCodeVO smsCodeVO = new SmsCodeVO();
        smsCodeVO.setPhone(phone);

        //验证码是否还有效
        String code = redisTemplate.opsForValue().get(phone);
        if (!StrUtil.isEmpty(code)) {
            smsCodeVO.setCode(code);
            smsCodeVO.setMessage("验证码还没过期");
            return Result.ok(smsCodeVO);
        }

        // 手机号是否注册
        User user = userService.selectByPhone(phone);// login(form.getName(), form.getPassword());
        //手机号没注册（对应用户不存在）
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException(BusinessExceptionEnum.USER_PHONE_EXIST);
        }

        //生成验证码
        code = String.format("%06d", ThreadLocalRandom.current().nextInt(1000000));//
        HashMap<String, Object> templateParam = new HashMap<>();
        templateParam.put("code", code);

        // 发送短信验证码
        smsUtil.sendSms(phone, templateParam);

        //短信验证码存储到redis中 有效期默认60秒
        if (StrUtil.isBlank(timeOut)) {
            timeOut = "60";
        }
        redisTemplate.opsForValue().set(phone, code, Long.parseLong(timeOut), TimeUnit.SECONDS);

        // 返回
        smsCodeVO.setCode(code);
        smsCodeVO.setMessage("验证码发送成功");
        return Result.ok(smsCodeVO);
    }

}
